<!-- 广告编辑弹窗 -->
<template>
  <el-dialog
    :title="isUpdate?'编辑邮件模板':'添加邮件模板'"
    :visible="visible"
    width="1100px"
    :destroy-on-close="true"
    :lock-scroll="false"
    :before-close="close"
    top="4vh"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px">

      <el-form-item label="模板类型" prop="title">
        <template>
<!--          <el-radio v-model="form.type" :label=1>邮件回访</el-radio>-->
<!--          <el-radio v-model="form.type" :label=2>主动发送</el-radio>-->
          <el-select clearable class="form_width" v-model="form.type">
            <el-option v-for="(item,index) in searchListData.template_type_list" :key="index" :label="item"
                       :value="parseInt(index)"/>
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="开启自动信的sku" prop="sku_list">
        <el-input
          :rows="3"
          clearable
          type="textarea"
          v-model="form.sku_list"
          placeholder="请输入sku,多个以;或换行分开"/>
      </el-form-item>

      <el-form-item label="模板名称:" prop="name">
        <el-input
          clearable
          :maxlength="128"
          v-model="form.name"
          show-word-limit
          placeholder="请输入模板名称"/>
      </el-form-item>
      <el-form-item label="邮件标题:" prop="title">
        <div>
          <el-button size="small" @click="titleFill('[用户名]')">[用户名]</el-button>
          <el-button size="small" @click="titleFill('[订单号]')">[订单号]</el-button>
          <el-button size="small" @click="titleFill('[收货地址]')">[收货地址]</el-button>
          <el-button size="small" @click="titleFill('[礼品名称]')">[礼品名称]</el-button>
          <el-button size="small" @click="titleFill('[产品名称]')">[产品名称]</el-button>
          <el-button size="small" @click="titleFill('[购买时间]')">[购买时间]</el-button>
          <el-button size="small" @click="titleFill('[激活成功时间]')">[激活成功时间]</el-button>
          <el-button size="small" @click="titleFill('[评价内容]')">[评价内容]</el-button>
          <el-button size="small" @click="titleFill('[留评链接]')">[留评链接]</el-button>
          <el-button size="small" @click="titleFill('[回访链接]')">[回访链接]</el-button>
        </div>
      </el-form-item>
      <el-form-item label="">
        <el-input
          clearable
          :maxlength="255"
          show-word-limit
          v-model="form.title"
          @blur="blurEvent"
          placeholder="请输入邮件标题"/>
      </el-form-item>
      <!-- 富文本编辑器 -->
      <el-form-item label="邮件内容:" prop="content">
        <tinymce-editor v-model="form.content"  :init="initEditor" ref="test"/>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="$emit('close')" >取消</el-button>
      <el-button
        type="primary"
        @click="save"
        :loading="loading">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor';

export default {
  name: 'EmailTemplateEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    searchList:Object
  },
  components: {TinymceEditor},
  data() {
    return {
      // 表单数据
      form: Object.assign({type: 1,title:''}, this.data),
      searchListData: Object.assign({}, this.searchList),
      // 表单验证规则
      rules: {
        title: [
          {required: true, message: '请输入邮件标题', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择模板类型', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入模板名称', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入邮件内容', trigger: 'blur'}
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      blurIndex: null,//记录光标位置
      blurIndexContent: null,//记录光标位置
      templateTypeList:[],//模板类型
    };
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({title:''}, this.data);
        this.isUpdate = true;
      } else {
        this.form = {
          content:'',
          title:''
        };
        this.isUpdate = false;
      }
    },
    searchList() {
      if (this.searchList) {
        this.searchListData = Object.assign({}, this.searchList);
      } else {
        this.searchListData = {};
      }
    }
  },
  computed: {
    // 初始化富文本
    initEditor() {
      return {
        height: 400,
        branding: false,
        skin_url: '/tinymce/skins/ui/oxide',
        content_css: '/tinymce/skins/content/default/content.css',
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        plugins: 'template code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount help',
        toolbar: 'template | fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl | help',
        toolbar_drawer: 'sliding',
        templates: [
          {title: '[用户名]', description: '将[用户名]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[用户名]'},
          {title: '[订单号]', description: '将[订单号]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[订单号]'},
          {title: '[收货地址]', description: '将[收货地址]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[收货地址]'},
          {title: '[礼品名称]', description: '将[礼品名称]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[礼品名称]'},
          {title: '[产品名称]', description: '将[产品名称]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[产品名称]'},
          {title: '[购买时间]', description: '将[购买时间]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[购买时间]'},
          {title: '[激活成功时间]', description: '将[激活成功时间]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[激活成功时间]'},
          {title: '[评价内容]', description: '将[评价内容]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[评价内容]'},
          {title: '[留评链接]', description: '将[留评链接]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[留评链接]'},
          {title: '[回访链接]', description: '将[回访链接]插入指定位置,发送邮件时会动态替换【激活买家管理】对应记录的内容', content: '[回访链接]'},
        ],
        images_upload_handler: (blobInfo, success, error) => {
          let file = blobInfo.blob();
          // 使用axios上传
          const formData = new FormData();
          formData.append('file', file, file.name);
          this.$http.post('/upload/uploadImage', formData).then(res => {
            if (res.data.code == 0) {
              success(res.data.data);
            } else {
              error(res.data.msg);
            }
          }).catch(e => {
            console.error(e);
            error(e.message);
          });
        },
        file_picker_types: 'media',
        file_picker_callback: () => {
        }
      }
    }
  },
  methods: {
    /*给邮件标题填充*/
    titleFill(val) {
      let index=this.blurIndex
      let str=this.form.title

      if (str == '' || str ==undefined){
        this.form.title = val;
      }else{
        this.form.title=str.slice(0, index) + val + str.slice(index);
      }
    },
    // 获取光标所在位置的index
    blurEvent(e) {
      this.blurIndex = e.srcElement.selectionStart;
    },
    setType(template_type_list)
    {
      this.templateTypeList = template_type_list;
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.form.title = encodeURIComponent(this.form.title);
          this.form.content = encodeURIComponent(this.form.content);
          this.$http.post('/emailTemplate/edit', this.form).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    /* 关闭页面 */
    close(hide) {
      if (hide) {
        hide();
      }
      this.$emit("done");
    }
  }
}
</script>

<style scoped>

::v-deep .el-button+.el-button{
  margin-left: 3px;
}

</style>
